package com.plian.system.controller.ms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.CacheUtil;
import com.plian.Tools.Func;
import com.plian.Tools.StringPool;
import com.plian.Tools.TokenUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.Behavioral;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.entity.ms.IssueSituation;
import com.plian.system.entity.ms.RectificationSituation;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.ms.IIssueSituationService;
import com.plian.system.service.ms.IRectificationSituationService;
import com.plian.system.vo.ms.RectificationSituationVO;
import com.plian.system.wrapper.ms.RectificationSituationWrapper;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;

/**
 * @author huzb
 * @create 2020-11-09 10:50
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("api/rectificationsituation")
public class RectificationSituationController {

    private IRectificationSituationService iRectificationSituationService;

    private IIssueSituationService iIssueSituationService;


    private RectificationSituationWrapper rectificationSituationWrapper;

    /**
     * 新增或修改
     */
    @PostMapping("/submit")
    @Resubmit(delaySeconds = 0)
    @LogOperation("整改情况-提交")
    public ObjResult submit(@Valid @RequestBody RectificationSituation rectificationSituation) {
        if (Optional.ofNullable(rectificationSituation.getStatus()).isPresent() &&
                rectificationSituation.getStatus() != FormStatusConstant.STASH){
            if (!iRectificationSituationService.checkIsExisted(rectificationSituation.getId(), rectificationSituation.getCode())){
                return new ObjResult(CustomCode.builder().message("单据编码已存在").code(1999).success(false).build());
            }
        }
        boolean result = iRectificationSituationService.submit(rectificationSituation);
        //修改问题状态
//        String issueSituationId = rectificationSituation.getIssueSituationId();
//        Long issueSituationid = Long.valueOf(issueSituationId);
//        IssueSituation issueSituation = new IssueSituation();
//        issueSituation.setId(issueSituationid);
        //查到的问题
//        IssueSituation detail = iIssueSituationService.getOne(Condition.getQueryWrapper(issueSituation));

        String rectificationSituation1 = rectificationSituation.getRectificationSituation();
//        if ("124001".equals(rectificationSituation1)){
//            detail.setIsRectification(1);
//            iIssueSituationService.submit(detail);
//        }else {
//            detail.setIsRectification(0);
//            iIssueSituationService.submit(detail);
//        }

        return result ? new ObjResult(CommonCode.SUCCESS) : new ObjResult(CommonCode.FAIL);
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @LogOperation("整改情况-删除")
    public ObjResult remove(@RequestBody PageData pd) {
        List<String> ids = (List<String>)pd.get("ids");
//        for (String id:ids){
//            RectificationSituation rectificationSituation = new RectificationSituation();
//            rectificationSituation.setId(Long.valueOf(id));
//            RectificationSituation detail = iRectificationSituationService.getOne(Condition.getQueryWrapper(rectificationSituation));
//
//            //修改问题状态
////            String issueSituationId = detail.getIssueSituationId();
////            Long issueSituationid = Long.valueOf(issueSituationId);
////            IssueSituation issueSituation = new IssueSituation();
////            issueSituation.setId(issueSituationid);
//            //查到的问题
////            IssueSituation detailis = iIssueSituationService.getOne(Condition.getQueryWrapper(issueSituation));
//
////            String rectificationSituation1 = detail.getRectificationSituation();
////            if ("124001".equals(rectificationSituation1)){
////                detailis.setIsRectification(0);
////                iIssueSituationService.submit(detailis);
////            }
//        }
        return iRectificationSituationService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
                ? new ObjResult(CommonCode.SUCCESS) : new ObjResult(CommonCode.FAIL);
    }

    /**
     * 详情
     */
    @PostMapping("/detail")
    @Behavioral
    public  R<RectificationSituationVO> detail(@Valid @RequestBody RectificationSituation rectificationSituation) {
        RectificationSituation detail = iRectificationSituationService.getOne(Condition.getQueryWrapper(rectificationSituation));
        R<RectificationSituationVO> objResult = new R<>(CommonCode.SUCCESS);
        RectificationSituationVO rectificationSituationVO = rectificationSituationWrapper.entityToVO(detail);
        objResult.setPageData(rectificationSituationVO);
        return objResult;
    }

    /**
     * 分页
     */
    @PostMapping("/list")
    public ListResult<RectificationSituationVO> list(@RequestBody Query query) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs()==null&&query.getDescs()==null){
            query.setDescs("create_time");
        }
        QueryWrapper<RectificationSituation> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new RectificationSituation()), entityList
        );
        TokenSearch<RectificationSituation> tokenSearch = new TokenSearch<>();
		tokenSearch.addTokenQuery(queryWrapper, query);

        IPage<RectificationSituation> pages = iRectificationSituationService.page(Condition.getPage(query), queryWrapper);
        List<RectificationSituationVO> rectificationSituationVOList = rectificationSituationWrapper.entityToVO(pages.getRecords());
        ListResult<RectificationSituationVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(rectificationSituationVOList);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

    /**
     * 问题整改报表
     */
    @PostMapping("/orgBydate")
    @Resubmit(delaySeconds = 0)
    public ListResult<PageData> orgBydate(@RequestBody PageData pageData) {
        List<PageData> pageDataList = iRectificationSituationService.orgBydate(pageData);
        ListResult<PageData> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(pageDataList);
        listResult.setTotal(pageDataList.size());
        return listResult;
    }

    /**
     * 年度整改清单
     */
    @PostMapping("/orgBymonth")
    @Resubmit(delaySeconds = 0)
    public ListResult<PageData> orgBymonth(@RequestBody PageData pageData) {
        List<PageData> pageDataList = iRectificationSituationService.orgBymonth(pageData);
        ListResult<PageData> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(pageDataList);
        listResult.setTotal(pageDataList.size());
        return listResult;
    }


    @PostMapping("/send-message")
    @ApiOperation(value = "发送消息", notes = "传入 id")
    @LogOperation("整改情况-消息发送")
    public R sendMessage(@RequestBody RectificationSituation situation) {
       iRectificationSituationService.sendMessage(situation);

        return R.success();
    }
    /**
     * 导入
     */
    @PostMapping("/excelCoverImport")
    @ApiOperation(value = "导入", notes = "传入文件")
    @LogOperation("整改情况-导入")
    public ObjResult excelCoverImport(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        String progressId = TokenUtil.getTokenUserId() + "_"+System.currentTimeMillis();
        CacheUtil.put("progress","progress",progressId + "#half:hour",0);
        InputStream inputStream = multipartFile.getInputStream();
        ServletRequestAttributes att = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        RequestContextHolder.setRequestAttributes(att, true);
        String token = att.getRequest().getHeader("token");
        att.setAttribute("token", token, RequestAttributes.SCOPE_SESSION);
        iRectificationSituationService.importExcel(progressId, inputStream);
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        PageData pd = new PageData();
        pd.put("progressId", progressId);
        objResult.setPageData(pd);
        return objResult;
    }

    /**
     * 导入进度查看
     */
    @GetMapping("/progress/{progressId}")
    @ApiOperation(value = "获取导入进度", notes = "传入进程id")
    public ObjResult progress(@PathVariable String progressId){
        Object data = CacheUtil.get("progress", "progress", progressId + "#half:hour");
        if(data != null && data instanceof String){
            if ("导入成功".equals(data)){
                ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
                PageData pd = new PageData();
                pd.put("data", 200);
                objResult.setPageData(pd);
                return objResult;
            }
            return new ObjResult(CustomCode.builder().message((String)data).code(1000).success(false).build());
        }
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        PageData pd = new PageData();
        pd.put("data", data);
        objResult.setPageData(pd);
        return objResult;
    }
    /**
     * 生成excel文件
     * @param
     * @return
     */
    @GetMapping("/exportImportFile")
    @ApiOperation(value = "生成excel文件")
    public ObjResult export(){
        PageData pd = new PageData();
        pd.put("key", iRectificationSituationService.export());
        ObjResult objResult = new ObjResult(CommonCode.SUCCESS);
        objResult.setPageData(pd);
        return objResult;
    }
    /**
     * 下载excel文件 并删除
     *
     * @param key
     * @param response
     */
    @GetMapping("/download/{key}")
//    @PassToken
    public void download(@PathVariable String key, HttpServletResponse response) {
        iRectificationSituationService.download(key, response);
    }
}
